package com.software.frontend.mine.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.software.frontend.R;
import com.software.frontend.fragments.Mine_MainFragment;
import com.software.frontend.loginAndRegist.entity.UserExtends;
import com.software.frontend.mine.utils.PictureProcessUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class EditPersonalInformationActivity extends AppCompatActivity {

    ImageView back, head;
    EditText userName, introduction;
    RadioGroup radioGroup;
    RadioButton female, male;
    Button submit;
    UserExtends userExtends;
    InputStream input;
    Bitmap bitmap;
    private String headUri = "center/head";
    private OkHttpClient okHttpClient = new OkHttpClient();
    private Gson gson = new Gson();
    private String upDateServiceLocation = "center/updateUserExtends";
    private String upHeadServiceLocation = "center/updateHead";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_personal_information);

        bindingViews();

        initViews();

        setListeners();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            // 从相册返回的数据
            Log.e(this.getClass().getName(), "Result:" + data.toString());
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                try {
                    input = this.getContentResolver().openInputStream(uri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                Bitmap bitmap = BitmapFactory.decodeStream(input);
                this.bitmap = bitmap;
                head.setImageBitmap(PictureProcessUtils.toRoundBitmap(bitmap));
            }
        }
    }

    private void bindingViews() {
        back = (ImageView) findViewById(R.id.button_back);
        head = (ImageView) findViewById(R.id.head);
        userName = (EditText) findViewById(R.id.username);
        introduction = (EditText) findViewById(R.id.introduction);
        radioGroup = (RadioGroup) findViewById(R.id.radio_group);
        female = (RadioButton) findViewById(R.id.female);
        male = (RadioButton) findViewById(R.id.man);
        submit = (Button) findViewById(R.id.submit_edit_personal_data);
    }

    private void initViews() {
        userExtends = (UserExtends) getIntent().getSerializableExtra("userExtends");
        Bitmap head = gson.fromJson(getIntent().getStringExtra("head"), Bitmap.class);
        if (userExtends == null || head == null) {
            setResult(Mine_MainFragment.RESULT_ERROR);
            finish();
        }else {
            this.head.setImageBitmap(head);
            userName.setText(userExtends.getName());
            introduction.setText(userExtends.getIntroduction());
            if (userExtends.getGemder().equals("male")){
                male.setSelected(true);
            }else {
                female.setSelected(true);
            }
        }

    }

    private void setListeners() {
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.button_back:
                        setResult(Mine_MainFragment.RESULT_CANCLE);
                        finish();
                        break;
                    case R.id.head:
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(intent, 2);
                        break;
                    case R.id.submit_edit_personal_data:
                        //访问后端，获取更新后的数据
                        String userName_str = userName.getText().toString();
                        String introduction_str = introduction.getText().toString();
                        String gender_str = null;
                        if (female.isSelected()){gender_str = "female";}
                        if (male.isSelected()){gender_str = "male";}
                        if (userName_str.equals("")){
                            Toast.makeText(EditPersonalInformationActivity.this, "请个输入用户名称", Toast.LENGTH_SHORT).show();
                        }else if(gender_str == null){
                            Toast.makeText(EditPersonalInformationActivity.this, "请选择好性别", Toast.LENGTH_SHORT).show();
                        }else {
                            //保存数据库数据
                            userExtends.setName(userName_str);
                            userExtends.setIntroduction(introduction_str);
                            userExtends.setGemder(gender_str);
                            FormBody formBody = new FormBody.Builder()
                                    .add("userExtends", gson.toJson(userExtends))
                                    .build();
                            Request request = new Request.Builder().url(getResources().getString(R.string.localhost) + upDateServiceLocation).post(formBody).build();
                            okHttpClient.newCall(request).enqueue(new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    e.printStackTrace();
                                    Log.i("onFailure", "访问失败");
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            setResult(Mine_MainFragment.RESULT_ERROR);
                                            finish();
                                        }
                                    });
                                }

                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    String s = response.body().string();
                                    boolean equals = userExtends.equals(gson.fromJson(s, UserExtends.class));
                                    userExtends = gson.fromJson(s, UserExtends.class);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Intent resultIntent = new Intent();
                                            resultIntent.putExtra("resultData", userExtends);
                                            resultIntent.putExtra("head", gson.toJson(bitmap));
                                            setResult(Mine_MainFragment.RESULT_OK, resultIntent);
                                            finish();
                                        }
                                    });
                                }
                            });
                            //保存头像到储存卡
//                            setPicToView(((BitmapDrawable)head.getDrawable()).getBitmap());
                            //上传头像到本地
//                            upLoadToCervice();
                        }
                        break;
                }
            }

            private void upLoadToCervice() {
                MediaType mediaType = MediaType.parse("multipart/form-data; charset=utf-8");
                OkHttpClient mOkHttpClent = new OkHttpClient();
                File file = new File(headUri);
                MultipartBody.Builder builder = new MultipartBody.Builder()
                        .setType(mediaType)
                        .addFormDataPart("file", "head.jpg",
                                RequestBody.create(MediaType.parse("image/jpg"), file))
                        .addFormDataPart("uid", String.valueOf(userExtends.getId()));

                RequestBody requestBody = builder.build();
                Request request1 = new Request.Builder()
                        .url(getResources().getString(R.string.localhost) + upHeadServiceLocation)
                        .post(requestBody)
                        .build();
                Call call = mOkHttpClent.newCall(request1);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, final IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.i("TAG", e.getMessage());
                                Toast.makeText(EditPersonalInformationActivity.this, "失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(EditPersonalInformationActivity.this, "更换成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
            }

            private void setPicToView(Bitmap bitmap) {
                String sdStatus = Environment.getExternalStorageState();
                if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                    return;
                }
                FileOutputStream b = null;
                File file = new File(headUri);
                file.mkdirs();// 创建文件夹
                String fileName = headUri + "/" + "head.jpg";//图片名字
                try {
                    b = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        //关闭流
                        b.flush();
                        b.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        back.setOnClickListener(onClickListener);
        head.setOnClickListener(onClickListener);
        submit.setOnClickListener(onClickListener);
    }
}